/*
 * @Author: zhoulf
 * @FilePath: /dg-refine-web/src/store/modules/user.js
 * @Date: 2022-06-07 20:14:24
 * @LastEditors: fastfan
 * @LastEditTime: 2022-12-08 22:32:16
 * @Description:
 */
import { tagsViewMutations } from '@cci/cp-frame-layout'
import {
  // getProjectFunsByCodeAndProjectId,
  loginByCode,
  // findByDeptId,
  refreshToken
} from '@/api/authApi'
function setMenuChildren (v) {
  return v.map((i) => {
    if (!i.children) {
      i.children = []
    } else {
      i.children = setMenuChildren(i.children)
    }
    return i
  })
}

/** userstore模块 */
const state = {
  token: window.$storage.get('token') || '', // 用户令牌
  userData: window.$storage.get('userData') || '',
  isRefresh: false, // 是否刷新
  idaastoken: '' // 统一认证token
  // authorityCode: window.$storage.get('authorityCode') || '', // 认证code
  // authorityType: window.$storage.get('authorityType') || '' // 认证type
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
    window.$storage.save('token', token)
    if (process.env.VUE_APP_ENV === 'development') {
      localStorage.setItem('refine-token', token)
    }
  },
  SET_IS_REFRESH: (state) => {
    state.isRefresh = true
  },
  SET_USERDATA: (state, userData) => {
    window.$storage.save('userData', userData)
    state.userData = userData
  },
  SET_IDAASTOKEN: (state, token) => {
    state.idaastoken = token
  }
  // SET_AUTHORITYCODE: (state, authorityCode) => {
  //   window.$storage.save('authorityCode', authorityCode)
  //   state.authorityCode = authorityCode
  // },
  // SET_AUTHORITYTYPE: (state, authorityType) => {
  //   window.$storage.save('authorityType', authorityType)
  //   state.authorityType = authorityType
  // }
}

const actions = {
  /**
   * 刷新token
   * @param commit
   * @param state
   * @constructor
   */
  // GetUserInfo
  GetUserInfo ({ commit }, params) {
    return new Promise((resolve, reject) => {
      loginByCode({ ...params })
        .then(({ data: { loginUser = {}, accessToken = '' } }) => {
          const user = {
            currentSiteId: loginUser.project.projectId,
            currentSiteName: loginUser.project.projectName,
            deptId: loginUser.deptment.deptId,
            deptName: loginUser.deptment.deptName,
            fullPath: '',
            groupId: loginUser.user.groupId,
            groupName: '',
            groupNo: '',
            ownRoles: loginUser.tcRoleList,
            platformId: '',
            userGrade: loginUser.user.userGrade,
            userId: loginUser.user.userId,
            userName: loginUser.user.userName,
            userNo: loginUser.user.userNo
          }

          commit('SET_TOKEN', accessToken)
          // commit('SET_TOKEN_VALID')
          commit('SET_USERDATA', user)
          commit('SET_IS_REFRESH')
          // 查询登录人部门组织结构表
          // dispatch('GetUserOrg', { deptId: loginUser.deptment.deptId })
          resolve(setMenuChildren(loginUser.projectFunctionList))
        })
        .catch((err) => reject(err))
    })
  },
  // 刷新获取新的token以及用户信息
  GetUserInfoByToken ({ commit }, data) {
    return new Promise((resolve, reject) => {
      refreshToken({ ...data })
        .then(({ data: { loginUser = {}, accessToken = '' } }) => {
          const user = {
            currentSiteId: loginUser.project.projectId,
            currentSiteName: loginUser.project.projectName,
            deptId: loginUser.deptment.deptId,
            deptName: loginUser.deptment.deptName,
            fullPath: '',
            groupId: loginUser.user.groupId,
            groupName: '',
            groupNo: '',
            ownRoles: loginUser.tcRoleList,
            platformId: '',
            userGrade: loginUser.user.userGrade,
            userId: loginUser.user.userId,
            userName: loginUser.user.userName,
            userNo: loginUser.user.userNo
          }

          commit('SET_TOKEN', accessToken)
          // commit('SET_TOKEN_VALID')
          commit('SET_USERDATA', user)
          commit('SET_IS_REFRESH')
          // 查询登录人部门组织结构表
          // dispatch('GetUserOrg', { deptId: loginUser.deptment.deptId })
          resolve(setMenuChildren(loginUser.projectFunctionList))
        })
        .catch((err) => reject(err))
    })
  },

  /**
   * 退出登陆
   * @param commit
   * @param useLogoutApi
   * @constructor
   */
  Logout ({ commit }) {
    return new Promise((resolve) => {
      tagsViewMutations.enabled(false)
      tagsViewMutations.enableCache(false)
      commit('SET_TOKEN', '')
      commit('SET_USERDATA', {})
      const ousideReg = new RegExp(window.location.host)
      let url = ''
      if (ousideReg.test(process.env.VUE_APP_THREECENTERLOCATION_OUT)) {
        url = process.env.VUE_APP_THREECENTERLOCATION_OUT
      } else {
        url = process.env.VUE_APP_THREECENTERLOCATION
      }
      resolve(url)
    })
  }
  // GetUserOrg({ commit }, params) {
  //   findByDeptId(params).then(({ code, data }) => {
  //     if (code === 0) {
  //       if (data) {
  //         commit('SET_AUTHORITYCODE', data.authorityCode, data.authorityCode)
  //         commit('SET_AUTHORITYTYPE', data.authorityType, data.authorityType)
  //       } else {
  //         commit('SET_AUTHORITYCODE', null)
  //         commit('SET_AUTHORITYTYPE', null)
  //       }
  //       // authorityType 类型  1:市监管,  2:镇街监管,  3:供气企业
  //       // authorityCode   null 市监管 镇街id 企业社会信用代码
  //     }
  //   })
  // }
}

export default {
  // namespaced: true,
  state,
  mutations,
  actions
}
